package com.hong.tomcat;

import com.hong.util.WebLoaderUtil;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by John on 2019/1/26.
 * Tomcat服务器
 */
public class TomcatServer {

    /**
     * 设置端口号
     */
    public static final int PORT = 8080;

    /**
     * 这里把servlet服务放在了webapps目录下
     */
    public static final String WEB_ROOT = "E:\\IDEAProjects\\tomcat-study\\webapps";

    private static ExecutorService threadPool = Executors.newCachedThreadPool();

    /**
     * 服务器启动初始化加载项目资源
     */
    public void init() {
        System.out.println("项目资源初始化加载");
        try {
            WebLoaderUtil.load();
        } catch (Exception e) {
            System.out.println("项目资源初始化加载error");
        }
    }

    private void start() {
        try {
            /**
             * Socket网络编程 BIO NIO Netty
             *  //端口号，最大链接数，ip地址
             * new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
             */
            ServerSocket serverSocket = new ServerSocket(PORT, 1, InetAddress.getByName("127.0.0.1"));
            System.out.println("Tomcat 服务已启动，地址：localhost ,端口：" + PORT);
            this.init();
            //持续监听
            while (!serverSocket.isClosed()) {
                Socket socket = serverSocket.accept();
                Runnable task = new SocketProcess(socket);
                //处理请求
                threadPool.execute(task);
            }
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        TomcatServer server = new TomcatServer();
        server.start();
    }

}
